import { Global, Module } from '@nestjs/common'
import { AuthController } from './auth.controller'
import { AuthService } from './auth.service'
import { UserModule } from '../user/user.module'
import { PassportModule } from '@nestjs/passport'
import { JwtModule } from '@nestjs/jwt'
import { ConfigModule, ConfigService } from '@nestjs/config'
import { ConfigEnum } from '../enum/config.enum'
import { JwtStrategy } from './jwt.strategy'
import { CaslAbilityService } from './casl-ability.service'

@Global()
@Module({
  imports: [
    UserModule,
    PassportModule,
    // JwtModule.register({
    //   secret: '', //jwt密匙，优先级1特别重要
    //   signOptions: { expiresIn: '60s' } //signOptions：配置选项 expiresIn：设置JWT的有效期
    // })
    // 优化：开发中和pro(生产)都需要secret：使用异步方式，DI系统可以读取到对应的数据=>github.com/nestjs/jwt的异步选项
    JwtModule.registerAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => {
        // console.log({
        //   secret: configService.get<string>(ConfigEnum.SECRET)
        // })
        return {
          secret: configService.get<string>(ConfigEnum.SECRET), //jwt密钥
          // 全局设置
          signOptions: { expiresIn: '1d' }
        }
      },
      inject: [ConfigService]
    })
  ],
  controllers: [AuthController],
  providers: [AuthService, JwtStrategy, CaslAbilityService],
  exports: [CaslAbilityService]
})
export class AuthModule {}
